package cn.webank.framework.retry.integration.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import cn.webank.framework.data.jedis.pool.JedisPartition;
import cn.webank.framework.data.jedis.pool.MultiJedisShardedPool;
import cn.webank.framework.retry.integration.RetryDAO;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.ShardedJedis;

@Repository("cn.webank.framework.retry.integration.dao.RetryDAO")
public class RetryRedisDAO implements RetryDAO {
	@Autowired
	@Qualifier("multiJedisShardedPool")
	private MultiJedisShardedPool multiJedisShardedPool;

	@Override
	public void saveRetryMessage(String namespace, String queue, String key,
			String json) {
		Jedis jedis = multiJedisShardedPool.getJedisPartition(key)
				.getReadWriteResource();
		String fk = formatKey(namespace, queue);
		jedis.lpush(fk, json);
	}

	@Override
	public String getRetryMessage(String namespace, String queue,
			ShardedJedis jedis) {
		String fk = formatKey(namespace, queue);
		List<String> l = jedis.brpop(fk);// jedis.brpop(5, fk);
		return l != null ? l.get(0) : null;
	}

	public long getRetryMessageSize(String namespace, String queue,
			ShardedJedis jedis) {
		String fk = formatKey(namespace, queue);
		return jedis.llen(fk);
	}

	public List<ShardedJedis> getJedises() {
		List<ShardedJedis> list = new ArrayList<ShardedJedis>();
		List<JedisPartition> jedisShardedPools = multiJedisShardedPool
				.getJedisPartitions();
		for (JedisPartition p : jedisShardedPools) {
			ShardedJedis resource = p.getWeBankShardedJedisPool().getResource();
			list.add(resource);
		}

		return list;
	}

	private String formatKey(String namespace, String queue) {
		return namespace + ":" + queue;
	}
}
